'use strict';

const Controller = require('egg').Controller;
const user_list = [];

class UsersController extends Controller {
    //显示用户列表
    async index (){
        const { ctx } = this;
        await ctx.render("index");
    }

    //显示添加页面
    async toAdd(){
        

    }

    //显示编辑页
    async toEdit(){

    }

    //发送用户列表
    async showList(){
        let user_list = await this.app.model.Users.findAll();
        this.ctx.body = {
            code:2000,
            msg:'ok',
            data:user_list
        };
    }

    //保存用户信息，存在id且大于0时为编辑，否则为添加
    async saveUser(){
        let user = this.ctx.request.body;
        let isUpdate = user.id > 0 ? true : false;
        let rs = '';
        if(!isUpdate){
            rs = await this.app.model.Users.create(user);
        }else{
            let pram = {name:user.name,age:user.age};
            let where = {'where':{id:user.id}};
            rs = await this.app.model.Users.update(pram,where);
        }
        if(!rs){
            this.ctx.body = {
                code:4000,
                msg:'数据保存失败',
                data:[],
            };
            return;
        }
        let user_list = await this.app.model.Users.findAll();
        this.ctx.body = {
            code:2000,
            msg:'保存成功',
            rs:rs,
            data:user_list
        };
    }

    //删除用户
    async delUser(){
        let where = {'where':{id:this.ctx.params.id}};
        let rs = await this.app.model.Users.destroy(where);
        if(!rs){
            this.ctx.body = {
                code:4000,
                msg:'删除失败',
                data:[]
            };
            return;
        }
        let user_list = await this.app.model.Users.findAll();
        this.ctx.body = {
            code:2000,
            msg:"删除成功",
            data:user_list
        };
    }

    //登录
    async login(){
        let info = this.ctx.request.body;
        if(info.userName == "admin" && info.userPwd == "123123"){
            let token = this.app.jwt.sign(info,this.app.config.jwt.secret);
            this.ctx.body = {
                code:2000,
                msg:'登录成功',
                data:token
            };
        }else{
            this.ctx.body = {
                code:4000,
                msg:'账户名或密码错误',
                data:info
            };
        }
    }

    getId(){
        let id = 0;
        for(var i=0;i<user_list.length;i++){
            id = user_list[i]['id'] > id ? user_list[i]['id'] : id;
        }
        return ++id;
    }
}

module.exports = UsersController;